import { auth } from './api'
import * as util from '../utils/index'
const debug = process.env.NODE_ENV === "development"

export function clearUserInfo(){
  setUserInfo(null)
}

export function setUserInfo(userInfo){
  if(debug){
    wx.setStorageSync('userInfo', userInfo)
  }
  const app = getApp()
  app.globalData.userInfo = userInfo
}

export function getUserInfo(){
  const app = getApp()
  return app.globalData.userInfo
}

export function getToken(){
  const userInfo = getUserInfo()
  if(userInfo && userInfo.token){
    return userInfo.token.token
  }
}

function checkSettingStatus() {
  // 判断是否是第一次授权，非第一次授权且授权失败则进行提醒
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success: function success(res) {
          var authSetting = res.authSetting;
          if (util.isEmptyObject(authSetting)) {
              console.log('首次授权');
              resolve(false)
          } else {
              console.log('不是第一次授权', authSetting);
              // 没有授权的提醒
              if (authSetting['scope.userInfo'] === false) {
                  wx.showModal({
                      title: '用户未授权',
                      content: '如需正常使用小程序功能，请按确定并在授权管理中选中“用户信息”，然后点按确定。最后再重新进入小程序即可正常使用。',
                      showCancel: false,
                      success: function (res) {
                          if (res.confirm) {
                              console.log('用户点击确定')
                              wx.openSetting({
                                  success: function success(res) {
                                      console.log('openSetting success', res.authSetting);
                                      resolve(res.authSetting['scope.userInfo'])
                                  }
                              });
                          }
                      }
                  })
              }else{
                resolve(true)
              }
          }
      }
  });
  })
}

export function
authTo(resolve, reject, login, info, parentId){
  auth({ code: login.code, userinfo: info.userInfo, parent_id: parentId }).then(res => {
    if (res.code === 200) {
      setUserInfo(res.data)
      resolve(mock(res.data))
    }else{
        reject(res.message)
    }
  });
}

function mock(userInfo){
  // return {...userInfo, recruited_at: 0}
  return userInfo
}

export function checkLogin(){
  const app = getApp()
  let info = app.globalData.userInfo
  if(info){
    return true
  }else{
    return false
  }
}

export default function(parentId = 0, userInfo = {}){
  return new Promise((resolve,reject) => {
    const app = getApp()
    let info = app.globalData.userInfo
    if(info){
        resolve(mock(info))
    }else if(debug && (info = wx.getStorageSync('userInfo'))){
        app.globalData.userInfo = info
        resolve(mock(info))
    }else{
      wx.navigateTo({
        url: '/pages/login/main'
      })
    }
})
}

